import Vue from "vue";
import Router from "vue-router";
import moduleRoutes from "./dynamicRoutes";
import Layout from "@/layout";
Vue.use(Router);
let { NODE_ENV } = process.env;
let envs = ["cn", "us"];

export const constantRoutes = [
  {
    path: "/",
    redirect: "/task/",
    hidden: true,
  },
  {
    path: "/help",
    component: () => import("@/views/helpCenter"),
    hidden: true,
  },
  {
    path: "/403",
    component: () => import("@/views/403"),
    hidden: true,
  },
  {
    path: "/404",
    component: () => import("@/views/404"),
    hidden: true,
  },
  // 404 page must be placed at the end !!!
  { path: "*", redirect: "/404", hidden: true },
];
const createRouter = () => {
  let moduleRouteArr = [];
  for (let key in moduleRoutes) {
    moduleRouteArr.push(...moduleRoutes[key]);
  }
  console.log("moduleRouteArr", moduleRouteArr);
  return new Router({
    mode: "history", // require service support
    base: "data",
    scrollBehavior: () => ({ y: 0 }),
    routes: [...moduleRouteArr, ...constantRoutes],
  });
};
const router = createRouter();
// Detail see: https://github.com/vuejs/vue-router/issues/1234#issuecomment-357941465
export function resetRouter() {
  const newRouter = createRouter();
  router.matcher = newRouter.matcher; // reset router
}
//为了解决正式环境 iframe嵌入h5界面 只有https才可以。当正式环境访问的时候，如果是http，自动跳转到https
router.beforeEach((to, from, next) => {
  if (envs.includes(NODE_ENV) && window.location.protocol === "http:") {
    let { host, pathname, search } = window.location;
    location.href = `https://${host}${pathname}${search}`;
  } else {
    next();
  }
});
export default router;
